import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.net.PortUnreachableException;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

public class SmartSensorJavaClient implements WindowListener, MenuListener {
	private SmartSensorJavaClient client;
	private SerialCommunication serial;
	private GUI window;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		new SmartSensorJavaClient();
	}

	public SmartSensorJavaClient() {
		client = this;
		initGUI();
		connectToArduino();

	}

	public void initGUI() {
		window = new GUI(this);
		window.getFrame().setVisible(true);
		window.getFrame().addWindowListener(client);
	}

	public void connectToArduino() {
		serial = new SerialCommunication();
		try {
			serial.initialize();

			// serial setup time
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Serial Connection Started");

			ProtocolHandler protocol = new ProtocolHandler(serial);
			System.out.println("received temp:"
					+ protocol.requestSetDouble("SETPARA",1,20.0));
		} catch (PortUnreachableException e1) {
			JOptionPane.showMessageDialog(window.getFrame(), e1.getMessage());
		}
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
	}

	@Override
	public void windowClosed(WindowEvent arg0) {
		serial.close();
	}

	@Override
	public void windowClosing(WindowEvent arg0) {
		serial.close();
	}

	@Override
	public void windowDeactivated(WindowEvent arg0) {
	}

	@Override
	public void windowDeiconified(WindowEvent arg0) {
	}

	@Override
	public void windowIconified(WindowEvent arg0) {
	}

	@Override
	public void windowOpened(WindowEvent arg0) {
	}

	@Override
	public void menuCanceled(MenuEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void menuDeselected(MenuEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void menuSelected(MenuEvent e) {
		if (e.getSource() instanceof JMenuItem) {
			if (((JMenuItem)e.getSource()).getActionCommand().equals("Reconnect")) {
				connectToArduino();
			}
		}
	}
}
